<template lang="pug">
  div.image-view.h-100p.relative
    img.absolute(:src="src" alt="" v-cpt-drag="" @load="posToCenter" :style="`transform:scale(${scale}) rotateZ(${rotate}deg)`")
    ul.toolbar
      li.btn(@click="clickHandler('zoomIn')")
        i.icon-zoom-in.icon
      li.btn(@click="clickHandler('zoomOut')")
        i.icon-zoom-out.icon
      li.btn(@click="clickHandler('rotateRight')")
        i.icon-cw.icon
      li.btn(@click="clickHandler('rotateLeft')")
        i.icon-ccw.icon
</template>

<script>
export default {
  props: {
    src: String
  },
  data() {
    return {
      scale: 1,
      step: 0.05,
      rotate: 0
    };
  },
  mounted() {
    this.setupEvents();
  },
  methods: {
    setupEvents() {
      this.$el.addEventListener('mousewheel', ev => {
        if (ev.wheelDelta > 0) {
          this.zoomIn();
        } else {
          this.zoomOut();
        }
      });
    },
    posToCenter() {
      const imgEl = this.$el.querySelector('img');
      const size = this.getImgSize();
      const x = (this.$el.offsetWidth - size.width) / 2;
      const y = (this.$el.offsetHeight - size.height) / 2;
      imgEl.style.left = x + 'px';
      imgEl.style.top = y + 'px';
    },
    getImgSize() {
      const imgEl = this.$el.querySelector('img');
      let size = {};
      size.width = imgEl.offsetWidth;
      size.height = imgEl.offsetHeight;
      if (size.width === 0) {
        size = this.getImgSize();
      }
      return size;
    },
    zoomIn() {
      this.scale += this.step * 2;
    },
    zoomOut() {
      this.scale -= this.step * 2;
    },
    rotateLeft() {
      this.rotate -= 90;
    },
    rotateRight() {
      this.rotate += 90;
    },
    clickHandler(command) {
      this[command]();
    }
  }
};
</script>

<style lang="less">
.image-view {
  img {
    transition: transform 0.3s;
    max-width: 100%;
    max-height: 100%;
  }
  .toolbar {
    position: absolute;
    right: 1rem;
    top: 0.5rem;
    .btn {
      font-size: 1rem;
      display: inline-block;
      padding: 2px;
      padding-left: 3px;
      border: 1px solid #ddd;
      margin-left: 2px;
      border-radius: 50%;
      cursor: pointer;
      text-align: center;
      user-select: none;
    }
  }
}
</style>
